import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author lzm
 * @date 2025/2/28 19:44
 * @description 演示线程池的
 */
public class RateLimitThreadPool {


    public static void main(String[] args) throws IOException {

        // 创建一个 HttpServer 实例，监听本地的 8000 端口
        HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);

        // 为不同的路径注册处理器
        server.createContext("/", new RootHandler());
        server.createContext("/order", new OrderHandler());

        // 设置线程池，这里使用单线程池
        server.setExecutor(null);
        // 启动服务器
        server.start();
        System.out.println("服务器已启动，监听端口 8000");
    }

    // 根路径处理器
    static class RootHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            String response = "Welcome to the root page!";
            exchange.getResponseHeaders().set("Content-Type", "text/plain; charset=UTF-8");
            exchange.sendResponseHeaders(200, response.length());
            OutputStream os = exchange.getResponseBody();
            os.write(response.getBytes());
            os.close();
        }
    }

    // 处理订单任务
    static class OrderHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            // 获取请求的 URI
            URI uri = exchange.getRequestURI();

            // 解析 URI 中的查询参数
            Map<String, String> queryParams = parseQuery(uri.getQuery());

            // 从查询参数中获取 name 参数
            String name = queryParams.getOrDefault("task", "default-task");

            // 获取线程池
            ThreadPoolExecutor threadPool = ThreadPoolManager.get();
            threadPool.execute(() -> {
                System.out.println("开始处理任务-" + name + "...");
                try {
                    // 模拟处理订单的耗时
                    TimeUnit.SECONDS.sleep(60);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });

            String response = "任务-" + name + "处理成功！";
            exchange.sendResponseHeaders(200, response.length());
            OutputStream os = exchange.getResponseBody();
            os.write(response.getBytes());
            os.close();
        }

        // 解析查询参数的方法
        private Map<String, String> parseQuery(String query) {
            Map<String, String> queryParams = new HashMap<>();
            if (query != null) {
                String[] pairs = query.split("&");
                for (String pair : pairs) {
                    int idx = pair.indexOf("=");
                    if (idx != -1) {
                        queryParams.put(pair.substring(0, idx), pair.substring(idx + 1));
                    }
                }
            }
            return queryParams;
        }
    }
}
